from django.db import models
from django.utils import timezone

class Permission(models.Model):
    """
    Permission table: defines specific permissions within the system.
    """
    permission_name = models.CharField(max_length=50, unique=True, verbose_name="Permission Name")
    description = models.TextField(null=True, blank=True, verbose_name="Description")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created At")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated At")

    class Meta:
        db_table = 'permissions'
        verbose_name = "Permission"
        verbose_name_plural = "Permissions"

    def __str__(self):
        return self.permission_name


class TemporaryPermission(models.Model):
    """
    Temporary Permission table: stores temporary permissions for users (including validity period).
    """
    user = models.ForeignKey('users.User', on_delete=models.CASCADE, verbose_name="User")  # Corrected to 'users.User'
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE, verbose_name="Permission")
    start_date = models.DateTimeField(verbose_name="Effective Start Time")
    end_date = models.DateTimeField(verbose_name="Expiration Time")
    is_active = models.BooleanField(default=True, verbose_name="Is Active")

    class Meta:
        db_table = 'temporary_permissions'
        verbose_name = "Temporary Permission"
        verbose_name_plural = "Temporary Permissions"

    def __str__(self):
        return f"{self.user.username} - {self.permission.permission_name} (Valid until {self.end_date})"

    # Check if the temporary permission is still valid
    def is_permission_active(self):
        return self.is_active and timezone.now() <= self.end_date